<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title></title>
		<style>
			*{padding: 0;margin: 0;}
			#snake-game{width: 100%;position: relative;}
			a{text-decoration: none;position: absolute;left: 20px;top: 100px;}
			.yard{ margin: 20px auto; width: 800px;}
			#score{position: absolute;left: 20px;top: 20px; color: red;}
		</style>
	</head>

	
	<body>
		<div id="snake-game">
			<div class="yard">
				<canvas id="snake-canvas" width="800" height="600"></canvas>
			</div>
			<div id="score">分数:0</div>
			<a href="index.html">再玩一次</a>
		</div>
	</body>
	
	<script type="text/javascript">
		var canvas = document.getElementById("snake-canvas");
		var context = canvas.getContext("2d");
		var scoreDiv = document.getElementById("score");
	
		var BLOCKSIZE = 20; //格子大小
		var CLOS = 40; // 列数
		var ROWS = 30;//行数
		
		var timer = null; // 计时器
		
		 var score = 0; //分数
	//		棋盘类
		function BackgroundDraw(){
			this.drawBack = function(){
				// 绘制横线
				for (var i = 0; i <= ROWS;i ++) {
					context.beginPath();
					context.moveTo(0,BLOCKSIZE *i);
					context.lineTo(BLOCKSIZE * CLOS,BLOCKSIZE * i);
					context.strokeStyle = "gray";
					context.stroke();
					context.save();
				}
				
				// 绘制竖线
				for (var i = 0;i <= CLOS;i++) {
					context.beginPath();
					context.moveTo(i *BLOCKSIZE, 0);
					context.lineTo(i *BLOCKSIZE, ROWS * BLOCKSIZE);
					context.strokeStyle = "gray";
					context.stroke();
					context.save();
					
				}
			}
		}
		
		// 蛇类
		function Snake(){
			// 存储蛇的位置
			this.positionArray = [];
			
			// 定义蛇移动的方向
			this.direction = 1; // 0 -左  1-右  2 -上  3-下
			
			this.snakeLength = 4;
			
			// 初始化(初始的时候假设长度为4)
			this.startInit = function(){
				for( var i = 0; i < this.snakeLength; i++){
                		this.positionArray[i] = {x: i * BLOCKSIZE, y: 0};
          		}
			}
			
			// 绘制蛇
			this.drawSnake = function(){
				for (var i = 0; i < this.positionArray.length;i++) {
					context.beginPath();
					if (i == this.positionArray.length - 1) {
						context.fillStyle = "red";
					} else{
						context.fillStyle = "green";
					}
					
					context.fillRect(this.positionArray[i].x,this.positionArray[i].y,BLOCKSIZE,BLOCKSIZE);
					context.strokeStyle = "white";
					context.strokeRect(this.positionArray[i].x,this.positionArray[i].y,BLOCKSIZE,BLOCKSIZE);
					context.save();
				}
			}
				//// 0 -左  1-右  2 -上  3-下
			// 蛇移动
			this.moveSnake = function(){
				switch (this.direction){
					case 0:
						this.positionArray.push({x:this.positionArray[this.snakeLength - 1].x - BLOCKSIZE,y:this.positionArray[this.snakeLength - 1].y});
						break;
					case 1:
						this.positionArray.push({x:this.positionArray[this.snakeLength - 1].x + BLOCKSIZE,y:this.positionArray[this.snakeLength - 1].y});
						break;
					case 2:
					this.positionArray.push({x:this.positionArray[this.snakeLength - 1].x,y:this.positionArray[this.snakeLength - 1].y - BLOCKSIZE});
						break;
					case 3:
					this.positionArray.push({x:this.positionArray[this.snakeLength - 1].x ,y:this.positionArray[this.snakeLength - 1].y + BLOCKSIZE});
						break;
					default:
						break;
				}
				//删除数组第一个元素
				this.positionArray.shift();
				
				// 重新绘制
				this.drawSnake();
			}
		}
		
		// 食物类
			function Food(){	
				this.foodX = parseInt(Math.random() * CLOS)* BLOCKSIZE;
				this.foodY = parseInt(Math.random() * ROWS)* BLOCKSIZE;
				// 增加新的食物
				this.addFood = function(){
					this.foodX = parseInt(Math.random() * CLOS)* BLOCKSIZE;
					this.foodY = parseInt(Math.random() * ROWS)* BLOCKSIZE;
				}
				// 绘制食物
				this.drawFood = function(){
					context.fillStyle = "yellow";
					context.fillRect(this.foodX,this.foodY,BLOCKSIZE,BLOCKSIZE);
					context.strokeStyle = "red";
					context.strokeRect(this.foodX,this.foodY,BLOCKSIZE,BLOCKSIZE);
					context.stroke();
					context.save();
				}
			}
		
		// 控制类，查看蛇是够吃到食物，蛇是否死亡
		function Handle(){
			this.isEat = function(snake,food){
				console.log(snake);
				if (snake.positionArray[snake.snakeLength - 1].x == food.foodX && snake.positionArray[snake.snakeLength - 1].y == food.foodY) {
					
				food.addFood();
					//蛇增加长度
				snake.snakeLength ++;
				// 蛇的身体添加一个坐标，这个坐标无所谓，因为下一次都会被删除
				snake.positionArray.unshift({x:0, y:0});
				
				// 加一分
				score ++;
				scoreDiv.innerHTML = "分数:" + score;
				
				}
			}	
			this.isDie = function(snake){
				// 检查是否碰到了边界
				if (snake.positionArray[snake.snakeLength - 1].x < 0 || snake.positionArray[snake.snakeLength - 1].x > BLOCKSIZE * CLOS || snake.positionArray[snake.snakeLength - 1].y < 0 || snake.positionArray[snake.snakeLength - 1].y > BLOCKSIZE * ROWS) {
					clearInterval(timer);
					alert("Game Over");	
					return true;
				}
				// 检查是否碰到了自己
				for (var i = 0; i< snake.snakeLength - 1; i++) {
					if (snake.positionArray[snake.snakeLength - 1].x == snake.positionArray[i].x && snake.positionArray[snake.snakeLength - 1].y == snake.positionArray[i].y) {
						clearInterval(timer);
						alert("Game Over");	
						return true;
					}
				}
				
				return false;
			}
			
		}
		
		// 画出背景格子
		var background = new BackgroundDraw();
		background.drawBack();	
		// 画蛇
		var snake = new Snake();
		snake.startInit();
		snake.drawSnake();
		// 食物对象
		var food = new Food();
		
		// 控制对象
		var handle = new Handle();
		
		
		handle.isEat(snake,food);
		
		// 让蛇移动起来
		 timer = setInterval(function(){
			context.clearRect(0,0,BLOCKSIZE *CLOS,BLOCKSIZE *ROWS);
			background.drawBack();			
				// 检查是否吃到了食物
				handle.isEat(snake,food);
				snake.moveSnake();	
				food.drawFood();
				// 检查是否死亡
				handle.isDie(snake);
			
		},300);
		

	
		document.onkeydown = function(event){
			var ev = event || window.event;
			switch (ev.keyCode){
				case 37: // 左
					if (snake.direction != 0 && snake.direction != 1) {
						snake.direction = 0;
					}
					break;
				case 38: // 上
					if (snake.direction != 2 && snake.direction != 3) {
						snake.direction = 2;
					}
					break;
				case 39: // 右
					if (snake.direction != 0 && snake.direction != 1) {
						snake.direction = 1;
					}
					break;
				case 40: // 下
					if (snake.direction != 2 && snake.direction != 3) {
						snake.direction = 3;
					}
					break;
				default:
					break;
			}
			
		}
		
		
	</script>
</html>
